using System;
using System.Drawing;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Weather
{
    public partial class NewMoodForm : Form
    {
        private const string API_KEY = AppConfig.WeatherApiKey;
        private ComboBox cmbMoodType;
        private TrackBar trackMoodScore;
        private Label[] scoreLabels;
        private Label lblWeather;
        private RichTextBox txtContent;
        private Button btnSave;
        private ComboBox cmbLocation;
        private Button btnSelectCity;
        private string currentCityCode = "310000"; // 默认上海

        public NewMoodForm()
        {
            InitializeComponents();
            _ = LoadCurrentWeatherAsync();  // 加载天气
        }

        private void InitializeComponents()
        {
            this.Text = "记录心情";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(245, 247, 250);
            this.Padding = new Padding(30);

            // 创建主滚动面板
            var mainScrollPanel = new Panel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true
            };

            var contentPanel = new Panel
            {
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(20),
                BackColor = Color.White,
                MinimumSize = new Size(700, 0)
            };

            // 心情类型选择
            var lblMoodType = new Label
            {
                Text = "今天的心情",
                Font = new Font("Microsoft YaHei", 14, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                AutoSize = true,
                Margin = new Padding(0, 0, 0, 10)
            };

            cmbMoodType = new ComboBox
            {
                Width = 200,
                Height = 35,
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("Microsoft YaHei", 12),
                FlatStyle = FlatStyle.Flat,
                Margin = new Padding(0, 0, 0, 20)
            };
            cmbMoodType.Items.AddRange(new string[] { "😊 开心", "😌 平静", "😢 难过", "😠 生气", "😰 焦虑" });
            cmbMoodType.SelectedIndex = 0;

            // 使用 FlowLayoutPanel 来自动排列控件
            var flowLayout = new FlowLayoutPanel
            {
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.TopDown,
                WrapContents = false,
                Dock = DockStyle.Top
            };

            // 添加所有控件到流式布局
            flowLayout.Controls.Add(lblMoodType);
            flowLayout.Controls.Add(cmbMoodType);

            // 心情评分区域
            var scorePanel = new Panel
            {
                BackColor = Color.FromArgb(250, 250, 250),
                Padding = new Padding(15),
                Height = 120,
                Width = contentPanel.Width - 40,
                Margin = new Padding(0, 0, 0, 20)
            };

            var lblScore = new Label
            {
                Text = "心情指数",
                Font = new Font("Microsoft YaHei", 12, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                AutoSize = true,
                Location = new Point(15, 15)
            };
            scorePanel.Controls.Add(lblScore);

            trackMoodScore = new TrackBar
            {
                Location = new Point(15, 45),
                Width = 400,
                Minimum = 1,
                Maximum = 5,
                Value = 3,
                TickFrequency = 1,
                TickStyle = TickStyle.Both,
                BackColor = Color.FromArgb(250, 250, 250)
            };
            scorePanel.Controls.Add(trackMoodScore);

            // 创建分数标签
            scoreLabels = new Label[5];
            var scoreTexts = new[] { "非常差", "较差", "一般", "不错", "很棒" };
            var scoreColors = new[] {
                Color.FromArgb(255, 99, 71),   // 红色
                Color.FromArgb(255, 165, 0),   // 橙色
                Color.FromArgb(72, 190, 117),  // 绿色
                Color.FromArgb(46, 139, 87),   // 深绿色
                Color.FromArgb(34, 139, 34)    // 森林绿
            };

            for (int i = 0; i < 5; i++)
            {
                scoreLabels[i] = new Label
                {
                    Text = $"{i + 1}分 - {scoreTexts[i]}",
                    AutoSize = true,
                    Font = new Font("Microsoft YaHei", 10),
                    ForeColor = i == 2 ? scoreColors[i] : Color.Gray,
                    Location = new Point(trackMoodScore.Left + (i * 95), trackMoodScore.Bottom + 5)
                };
                scorePanel.Controls.Add(scoreLabels[i]);
            }

            trackMoodScore.ValueChanged += (s, e) =>
            {
                for (int i = 0; i < scoreLabels.Length; i++)
                {
                    scoreLabels[i].ForeColor = (i + 1 == trackMoodScore.Value) ? 
                        scoreColors[i] : Color.Gray;
                }
            };

            flowLayout.Controls.Add(scorePanel);

            // 天气显示
            lblWeather = new Label
            {
                Text = "当前天气：晴",
                Font = new Font("Microsoft YaHei", 12),
                ForeColor = Color.FromArgb(64, 64, 64),
                BackColor = Color.FromArgb(250, 250, 250),
                Padding = new Padding(15),
                AutoSize = true,
                Margin = new Padding(0, 0, 0, 10)
            };
            flowLayout.Controls.Add(lblWeather);

            // 添加选择城市按钮
            btnSelectCity = new Button
            {
                Text = "选择当前城市",
                Width = 150,
                Height = 35,
                Font = new Font("Microsoft YaHei", 11),
                BackColor = Color.FromArgb(240, 240, 240),
                ForeColor = Color.FromArgb(64, 64, 64),
                FlatStyle = FlatStyle.Flat,
                Cursor = Cursors.Hand,
                Margin = new Padding(0, 0, 0, 20)
            };
            btnSelectCity.FlatAppearance.BorderSize = 1;
            btnSelectCity.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
            btnSelectCity.Click += BtnSelectCity_Click;
            flowLayout.Controls.Add(btnSelectCity);

            // 日记内容
            var lblContent = new Label
            {
                Text = "记录此刻的心情...",
                Font = new Font("Microsoft YaHei", 12, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                AutoSize = true,
                Margin = new Padding(0, 0, 0, 10)
            };
            flowLayout.Controls.Add(lblContent);

            txtContent = new RichTextBox
            {
                Size = new Size(contentPanel.Width - 40, 200),
                Font = new Font("Microsoft YaHei", 11),
                BorderStyle = BorderStyle.None,
                BackColor = Color.FromArgb(250, 250, 250),
                Margin = new Padding(0, 0, 0, 20)
            };
            flowLayout.Controls.Add(txtContent);

            // 保存按钮
            btnSave = new Button
            {
                Text = "保存心情",
                Width = 150,
                Height = 45,
                Font = new Font("Microsoft YaHei", 12, FontStyle.Bold),
                BackColor = Color.FromArgb(72, 190, 117),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Cursor = Cursors.Hand,
                Margin = new Padding(0, 0, 0, 20)
            };
            btnSave.FlatAppearance.BorderSize = 0;
            btnSave.Click += BtnSave_Click;
            flowLayout.Controls.Add(btnSave);

            // 添加布局到面板
            contentPanel.Controls.Add(flowLayout);
            mainScrollPanel.Controls.Add(contentPanel);
            this.Controls.Add(mainScrollPanel);

            // 调整内容面板的位置使其居中
            contentPanel.Location = new Point(
                (mainScrollPanel.Width - contentPanel.Width) / 2,
                0
            );

            // 窗体大小改变时重新调整内容面板位置
            this.Resize += (s, e) =>
            {
                contentPanel.Location = new Point(
                    (mainScrollPanel.Width - contentPanel.Width) / 2,
                    0
                );
            };
        }

        // 恢复原有的保存功能
        private void BtnSave_Click(object sender, EventArgs e)
        {
            string sql = @"INSERT INTO user_moods 
                (user_id, mood_type, mood_score, weather, content) 
                VALUES (@userId, @moodType, @moodScore, @weather, @content)";

            // 从表情符号中提取心情类型（去掉emoji）
            string moodType = cmbMoodType.Text.Substring(3);

            MySqlParameter[] parameters = {
                new MySqlParameter("@userId", MySqlDbType.Int32) { Value = CurrentUser.Id },
                new MySqlParameter("@moodType", MySqlDbType.VarChar) { Value = moodType },
                new MySqlParameter("@moodScore", MySqlDbType.Int32) { Value = trackMoodScore.Value },
                new MySqlParameter("@weather", MySqlDbType.VarChar) { Value = lblWeather.Text.Replace("当前天气：", "") },
                new MySqlParameter("@content", MySqlDbType.Text) { Value = txtContent.Text }
            };

            try
            {
                DBHelper.ExecuteNonQuery(sql, parameters);
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 恢复天气加载功能
        private async Task LoadCurrentWeatherAsync()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    string url = $"https://restapi.amap.com/v3/weather/weatherInfo?key={API_KEY}&city={currentCityCode}&extensions=base";
                    var response = await client.GetStringAsync(url);
                    var weatherData = JObject.Parse(response);
                    
                    string weather = weatherData["lives"][0]["weather"].ToString();
                    lblWeather.Text = $"当前天气：{weather}";
                }
            }
            catch
            {
                lblWeather.Text = "当前天气：未知";
            }
        }

        // 清理表单方法（如果需要）
        private void ClearForm()
        {
            cmbMoodType.SelectedIndex = 0;
            trackMoodScore.Value = 3;
            txtContent.Clear();
        }

        // 添加选择城市按钮的点击事件处理方法
        private async void BtnSelectCity_Click(object sender, EventArgs e)
        {
            using (var cityForm = new Form())
            {
                cityForm.Text = "选择城市";
                cityForm.Size = new Size(300, 150);
                cityForm.StartPosition = FormStartPosition.CenterParent;
                cityForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                cityForm.MaximizeBox = false;
                cityForm.MinimizeBox = false;

                var cityCombo = new ComboBox
                {
                    Location = new Point(20, 20),
                    Width = 240,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                    Font = new Font("Microsoft YaHei", 11)
                };

                // 添加一些主要城市
                var cities = new Dictionary<string, string>
                {
                    {"北京", "110000"},
                    {"上海", "310000"},
                    {"广州", "440100"},
                    {"深圳", "440300"},
                    {"杭州", "330100"},
                    {"南京", "320100"},
                    {"成都", "510100"},
                    {"重庆", "500000"},
                    {"武汉", "420100"},
                    {"西安", "610100"}
                };

                foreach (var city in cities)
                {
                    cityCombo.Items.Add(city.Key);
                }
                cityCombo.SelectedItem = "上海"; // 默认选中上海

                var btnConfirm = new Button
                {
                    Text = "确定",
                    Location = new Point(100, 60),
                    Width = 80,
                    Height = 30,
                    DialogResult = DialogResult.OK
                };

                cityForm.Controls.AddRange(new Control[] { cityCombo, btnConfirm });

                if (cityForm.ShowDialog() == DialogResult.OK)
                {
                    string selectedCity = cityCombo.SelectedItem?.ToString();
                    if (!string.IsNullOrEmpty(selectedCity) && cities.ContainsKey(selectedCity))
                    {
                        currentCityCode = cities[selectedCity];
                        btnSelectCity.Text = $"当前城市：{selectedCity}";
                        await LoadCurrentWeatherAsync(); // 重新加载天气
                    }
                }
            }
        }
    }
} 
